/**
 * (判断是不是苹果设备)
 * @returns true 是苹果     false 不是
 */
export const isAppleDevice = () => {
    // if (/GyPackage/i.test(navigator.userAgent)) {
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return true
    } else {
        return false
    }
}
// 判断是否为微信
export const isWeiXin = () => {
    let ua = window.navigator.userAgent
    if (ua.match(/MicroMessenger/i) === 'MicroMessenger' || ua.match(/MicroMessenger/i) === 'micromessenger') {
        return true
    } else {
        return false
    }
}

/*
* 是否移动设备：返回Boolean。
*/
export const isMobile = () => {
    let myUA = window.navigator.userAgent.toLowerCase()
    let isMobile = /(?:micromessenger|mobile|iphone|ipod|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|windows phone|win ce|nokia)/i.test(myUA)
    if (isMobile) {
        return true
    } else {
        return false
    }
}

// 时间插件
export const formatDate = (timestamp, type, difference, utc) => {
    timestamp = timestamp || ''
    type = type || ''
    utc = utc || null
    difference = difference || null
    var getTimestamp = ''
    if (difference) {
        timestamp = +timestamp + difference * 60 * 60 * 1000
    }
    if (utc) {
        let u = new Date()
        let u2 = u.getTimezoneOffset() / 60
        // 获得本地时区utc=utc?parseFloat(utc):u2*60*60*1000
        // 格式化传入时间
        if (u2 < 0) {
            getTimestamp = timestamp + Math.abs(u2 * 60 * 60 * 1000)
        } else {
            getTimestamp = timestamp - (u2 * 60 * 60 * 1000)
        }
    } else {
        getTimestamp = timestamp
    }
    const rt = new Date(getTimestamp)
    const y = rt.getFullYear()

    const hourStr = rt.getHours() < 10 ? ('0' + rt.getHours()) : rt.getHours()
    const minStr = rt.getMinutes() < 10 ? ('0' + rt.getMinutes()) : rt.getMinutes()
    const SecStr = rt.getSeconds() < 10 ? ('0' + rt.getSeconds()) : rt.getSeconds()

    let m = rt.getMonth() + 1
    let d = rt.getDate()
    m = m < 10 ? ('0' + m) : m
    d = d < 10 ? ('0' + d) : d

    if (hourStr && minStr && m && y) {
        if (type && type === 'HH:MM') {
            return hourStr + ':' + minStr
        }
        if (type && type === 'MM-DD') {
            return m + '-' + d
        }
        if (type && type === 'YYYY-MM-DD') {
            return y + '-' + m + '-' + d
        }
        if (type && type === 'YYYY-MM') {
            return y + '-' + m
        }
        if (type && type === '年月') {
            return y + '年' + m + '月'
        }
        if (type && type === '年-月-日') {
            return y + ' 年 ' + m + ' 月 ' + d + ' 日'
        }
        if (type && type === 'YYYY.MM.DD') {
            return y + '.' + m + '.' + d
        }
        if (type && type === 'YYYY-MM-DD HH:MM') {
            return y + '-' + m + '-' + d + ' ' + hourStr + ':' + minStr
        }
        if (type && type === '日 00:00') {
            return d + '日 ' + hourStr + ':' + minStr
        }
        if (type && type === 'YYYY-MM-DD HH:MM:SS') {
            return y + '-' + m + '-' + d + ' ' + hourStr + ':' + minStr + ':' + SecStr
        }
        if (type && type === 'HH:MM:SS') {
            return hourStr + ':' + minStr + ':' + SecStr
        }

        if (type && type === 'common') {
            return (
                rt.getFullYear() + '年' +
        (rt.getMonth() + 1) + '月' +
        rt.getDate() + '日 ' +
        hourStr + ':' +
        minStr
            )
        }

        return (
            m + '月' +
      d + '日 ' +
      hourStr + ':' +
      minStr
        )
    } else {
        return ''
    }
}

// 获取地址栏参数
export const getUrlParam = () => {
    var url = decodeURI(location.search) // 转换被转译的中文
    var object = {}
    if (url.indexOf('?') !== -1) { // url中存在问号，也就说有参数。
        var str = url.substr(1) // 得到?后面的字符串
        var strs = str.split('&') // 将得到的参数分隔成数组[id="123456",Name="bicycle"];
        for (var i = 0; i < strs.length; i++) {
            object[strs[i].split('=')[0]] = strs[i].split('=')[1]
        }
    }
    return object
}

// 传递地址栏路径获取参数
export const getStrUrlParam = (str, name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = str && str.split("?")[1].match(reg); //匹配目标参数
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null; //返回参数值
}
/**
 * 数字过长时单位转换
 * @param {Number} val 初始值
 * @param {String} unit 拼接的单位
 * @return {String} 格式化后的值
 */
export const conversion = (val) => {
    let unit = ''
    if (val > 99999999) {
        unit = '亿'
        val = (val / 100000000).toFixed(2)
        let valArr = val.split('.')
        let point = valArr[1]
        if (point === '00') {
            return valArr[0] + unit
        } else if (point % 10 === 0) {
            return valArr[0] + '.' + point / 10 + unit
        } else {
            return val + unit
        }
    }
    if (val > 9999) {
        unit = '万'
        val = (val / 10000).toFixed(2)
        let valArr = val.split('.')
        let point = valArr[1]
        if (point === '00') {
            return valArr[0] + unit
        } else if (point % 10 === 0) {
            return valArr[0] + '.' + point / 10 + unit
        } else {
            return val + unit
        }
    }
    return val
}

/**
 * 获取localStorage
 */
export const getStore = name => {
    if (!name) return
    return window.localStorage.getItem(name)
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
    if (!name) return
    window.localStorage.removeItem(name)
}

/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
    if (!name) return
    if (typeof content !== 'string') {
        content = JSON.stringify(content)
    }
    window.localStorage.setItem(name, content)
}

/**
 * 获取style样式值
 */
export const getStyle = (curEle, attr) => {
    let val, reg
    // scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
    if (attr === 'scrollTop') {
        val = curEle.scrollTop
    } else if (attr === 'opacity') {
        val = curEle.currentStyle['filter'] // 'alpha(opacity=12,345)'
        reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i
        val = reg.test(val) ? reg.exec(val)[1] / 100 : 1
    } else if (curEle.currentStyle) {
        val = curEle.currentStyle[attr]
    } else {
        val = document.defaultView.getComputedStyle(curEle, null)[attr]
    }
    return parseFloat(val)
}

export const randomString = (len = 32) => {
    len = len || 32
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = chars.length
    var str = ''
    for (let i = 0; i < len; i++) {
        str += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return str
}

/**
 * @param {obj} data 遍历的表格对象
 * @param {string} tabList 表格对象中需要拆分的数组名
 * @param {arr} formatData 表格中拆分部分展示的键名集合
 * @param {obj} maps 拆分后需要有默认值
 */
export const tableFormat = (data, tabList, formatData, maps) => {
    let table = []
    let formatList = []
    let tableIndex = 0
    for (let i = 0; i < data.length; i++) {
        formatList = data[i][tabList]
        if (formatList.length > 0) {
            if (formatList.length < 2 && formatList[0] !== null) { // 如果用户抽奖数据少于两条，则直接插入
                // formatList[0] !== null 为账号管理页面添加。发现有此格式数据
                table.push(data[i])
                formatData.map(item => {
                    table[tableIndex][item] = formatList[0][item] || formatList[0][item] === 0 ? formatList[0][item] : maps[item]
                })
                table[tableIndex]['tableIndex'] = i + 1
                tableIndex++
            }
            if (formatList.length >= 2) { // 抽奖数据多余1条时，将每一条循环到table中，表格合并使用
                let formatObj = {}
                for (let j = 0; j < formatList.length; j++) {
                    table.push(data[i])
                    formatData.map(item => {
                        formatObj[item] = formatList[j][item] || formatList[j][item] === 0 ? formatList[j][item] : maps[item]
                    })
                    formatObj.merge = 0
                    table[tableIndex] = JSON.parse(JSON.stringify(Object.assign(table[tableIndex], formatObj)))
                    if (j === 0) { // 添加合并单元格标识
                        table[tableIndex].merge = formatList.length
                    }
                    table[tableIndex]['tableIndex'] = i + 1
                    tableIndex++
                }
            }
        } else {
            table.push(data[i])
            table[tableIndex]['tableIndex'] = i + 1
            tableIndex++
        }
    }
    return table
}
// 分割数组为指定长度二维数组
export const subArrayGroup = (array, subGroupLength) => {
    let index = 0
    let subArray = []
    while (index < array.length) {
        subArray.push(array.slice(index, (index += subGroupLength)))
    }
    return subArray
}

/**
 * 获取近几天的时间
 * 如近7天  getDaysTime(-7)
 * */
function doHandleMonth(month){
　　var m = month;
　　if(month.toString().length == 1){
　　　　m = "0" + month;
　　}
　　return m;
}
export const getDaysTime = (day) => {
　　var today = new Date();
　　var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
　　today.setTime(targetday_milliseconds); //注意，这行是关键代码
　　var tYear = today.getFullYear();
　　var tMonth = today.getMonth();
　　var tDate = today.getDate();
　　tMonth = doHandleMonth(tMonth + 1);
　　tDate = doHandleMonth(tDate);
　　return tYear+"-"+tMonth+"-"+tDate;
}